using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BA2009.Entities;
using BA2009.Services;
using MvcContrib.Pagination; 
     
namespace BA2009.Web.Controllers
{
     public class BannerPositionsFormViewModel
     {
         public BannerPosition BannerPosition
          {
               get;
               private set;
          }

          public IList<Banner> Banners
          {
               get;
              private set;
          }

          public BannerPositionsFormViewModel( BannerPosition position, IList<Banner> banners )
          {
              this.BannerPosition = position;
              this.Banners = banners;
          }

     }
     
         
     public class BannerPositionsController : Controller
      {
        
          //Declaring Service from positions
          public IBannerPositionService Service
          {
               get;
               private set;
          }

          public BannerPositionsController( IBannerPositionService service )
          {
               //if (service==null)
               //     service= new BannerPositionService();
               this.Service= service;
          }

          public BannerPositionsController() : this(null)
          {
          }
          //
        // GET: /BannerPositions/

        public ActionResult Index(int page)
        {
            //int id = 0;
            //if (Request.Params.AllKeys.Contains("page"))
            //{
            //    id= Convert.ToInt32(Request.Params.Get("page"));
            //}
            var listPosition = Service.GetBannerPositionByPageId(page);

             return View(listPosition);
        }

        //
        // GET: /BannerPositions/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /BannerPositions/Create

        public ActionResult Create()
        {
             Entities.BannerPosition position= new BannerPosition();
             IList<Banner> banners = Service.GetAllBanner();
             position.PageID = Convert.ToInt32(Request.Params["page"]);
          
             return View(new BannerPositionsFormViewModel(position,banners));
        } 

        //
        // POST: /BannerPositions/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                int pageId = Convert.ToInt32(collection.Get("PageID"));

                 var keys= collection.AllKeys.AsQueryable();

                 string name= collection.Get("BannerPositionName");
                 string code=collection.Get("Code");
                 string des= collection.Get("Description");
                 //int pageId=1;//Current setting default value. will be changed later./quyenbc9/4/2009

                 BannerPosition position = new BannerPosition
                 {
                      BannerPositionName=name,
                      Code= code,
                      Description=des,
                      PageID= pageId
                 };

                 //int positionId= Service.Add(position);
                 //Map data to BannerPositionMap table.
                 IList<int> checkedIds= this.GetCheckedResources(keys);
                 IList<MapEntity> banners = null;

                 if (checkedIds.Count>0)
                 {
                      banners=this.MakeMapEntities(0, checkedIds);
                 }
                 object [] maps= new object [] { banners };
                 int mapId=Service.Add(position, maps);

                 return RedirectToAction("Index", new { page=pageId});
            }
            catch( Exception ex)
            {
                 Utility.ExceptionManager.Handle(ex);
                 return View();
            }
        }

        //
        // GET: /BannerPositions/Edit/5
 
        public ActionResult Edit(int id)
        {
            BannerPosition bannerPosition = Service.GetById(id);

            IList<Banner> banners = Service.GetAllBanner();

            BannerPositionsFormViewModel model = new BannerPositionsFormViewModel(bannerPosition, banners);

            return View(model);
        }

        //
        // POST: /BannerPositions/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(FormCollection formCollections)
        {
            try
            {

                var keys = formCollections.AllKeys.AsQueryable();

                int pageId = Convert.ToInt32(formCollections.Get("PageID"));
                int id = Convert.ToInt32(formCollections.Get("BannerPositionID"));
                string code = formCollections.Get("Code");
                string bannerPositionName = formCollections.Get("BannerPositionName");

                BannerPosition bannerPosition = new BannerPosition
                {
                    BannerPositionID = id,
                    Code = code,
                    BannerPositionName = bannerPositionName,
                    PageID=pageId
                };

                //int newid = Service.Add(bannerPosition);

                // Add data to BannerPositionResource table
                IList<int> checkedIds = this.GetCheckedMaps(keys, "chkBannerPositionID_");
                IList<MapEntity> positionMaps = null;
                if (checkedIds.Count > 0)
                {
                    positionMaps = this.MakeMapEntities(id, checkedIds);
                }
                else
                {
                    positionMaps = new List<MapEntity>();
                    positionMaps.Add(new MapEntity { ID1 = id, ID2 = 0 });
                }



                object[] maps = new object[] { positionMaps };
                int newId = Service.Update(bannerPosition, maps);
                return RedirectToAction("Index");

            }
            catch (Exception ex)
            {
                Utility.ExceptionManager.Handle(ex);
                return View();
            }
        }

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(int id)
        {
            var position = Service.GetById(id);
            var ret = Service.Delete(position);

            return this.Json(ret);
        }

      #region Private Methods
        private IList<MapEntity> MakeMapEntities( int id1, IList<int> id2s )
        {
             IList<MapEntity> ret = new List<MapEntity>();
             foreach (int id2 in id2s)
             {
                  var map = new MapEntity
                  {
                       ID1 = id1,
                       ID2 = id2
                  };
                  ret.Add(map);
             }

             return ret;
        }


        private IList<int> GetCheckedResources( IQueryable<string> keys )
        {
             IList<int> ret = new List<int>();
             var checks = (from k in keys
                           where k.StartsWith("chkBannerPositionID_")
                           select k).ToList();

             if (checks != null && checks.Count > 0)
             {
                  for (int i = 0; i < checks.Count; i++)
                  {
                       var id = Convert.ToInt32(checks [ i ].Substring(checks [ i ].LastIndexOf('_')+1));

                       ret.Add(id);
                  }
             }

             return ret;
        }

        private IList<int> GetCheckedMaps(IQueryable<string> keys, string formStartName)
        {
            IList<int> ret = new List<int>();
            var checks = (from k in keys
                          where k.StartsWith(formStartName)
                          select k).ToList();

            if (checks != null && checks.Count > 0)
            {
                for (int i = 0; i < checks.Count; i++)
                {
                    var id = Convert.ToInt32(checks[i].Substring(checks[i].LastIndexOf('_') + 1));

                    ret.Add(id);
                }
            }

            return ret;
        }

      #endregion

      }
}
